﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StyleMVVM.Data.Transform
{
	public sealed class GenericListTransform : ITransformStrategy
	{
		public bool IsLooseTranform { get; private set; }

		public ITransformService TransformService { get; set; }

		public void Initalize()
		{
		}

		public object Transform(object valueIn, Type transformHint)
		{
			IList currentList = valueIn as IList;
			IList returnValue = null;

			if (currentList != null)
			{
				if (transformHint.IsArray)
				{
					returnValue = Activator.CreateInstance(transformHint, currentList.Count) as IList;

					Type elementType = returnValue.GetType().GetElementType();

					for (int i = 0; i < currentList.Count; i++)
					{
						returnValue[i] =
							TransformService.Transform(currentList[i], elementType);
					}
				}
				else if (transformHint.IsConstructedGenericType)
				{
					returnValue = Activator.CreateInstance(transformHint) as IList;

					Type genericTypeArg = transformHint.GenericTypeArguments[0];

					for (int i = 0; i < currentList.Count; i++)
					{
						returnValue.Add(
							TransformService.Transform(currentList[i], genericTypeArg));
					}
				}
			}

			return returnValue;
		}
	}
}